package net.lainiao.reptile;

import net.lainiao.base.model.ReptileFilter;
import net.lainiao.base.model.ReptileTopic;
import net.lainiao.service.service.ReptileFilterService;
import net.lainiao.service.service.ReptileTopicService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/1/10.
 */
public class FilterHelper {
    private static HashMap<Integer,List<Pattern>> hashMap=new HashMap<>();
    private static RedisHelper redisHelper=null;
    public static boolean isAllow(String url,int tid){
        if(StringUtils.isBlank(url)){
            return false;
        }

        if(!FilterHelper.isAllowRegex(url,tid)){
            return false;
        }

        if(FilterHelper.isProcessed(url)){
            return false;
        }
        return true;
    }

    public static boolean isProcessed(String url){
        return FilterHelper.redisHelper.isProcessed(url);
    }
    //判断过滤条件
    private static boolean isAllowRegex(String url, int tid) {
        for(Pattern regex:hashMap.get(tid)){
            if(!regex.matcher(url).find()){
                return false;
            }
        }
        return true;
    }

    //初始化规则
    public static void initHashMap() {
        hashMap.isEmpty();
        ApplicationContext context=ApplicationCommon.applicationContext;
        ReptileTopicService reptileTopicService=context.getBean(ReptileTopicService.class);
        List<ReptileTopic> topics=reptileTopicService.getALL();
        ReptileFilterService filterService=context.getBean(ReptileFilterService.class);
        for(ReptileTopic topic:topics){
            List<Pattern> patterns=new ArrayList<>();
            List<ReptileFilter> filters=filterService.getListForTid(topic.getId());
            for(ReptileFilter filter:filters){
                Pattern pattern=Pattern.compile(filter.getRule());
                patterns.add(pattern);
            }
            hashMap.put(topic.getId(),patterns);
        }
        if(FilterHelper.redisHelper==null){
            FilterHelper.redisHelper=context.getBean(RedisHelper.class);
        }
        System.out.println("Filter Helper InitHashMap");
    }
}
